package cn.mdmm.controller.news;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.mdmm.common.MessageConstant;
import cn.mdmm.common.SpringSecurityUtils;
import cn.mdmm.controller.BaseController;
import cn.mdmm.entity.news.NewsInfoModel;
import cn.mdmm.entity.response.ResponseBodyToGridData;
import cn.mdmm.entity.response.ResponseBodyToOne;
import cn.mdmm.entity.system.SysUser;
import cn.mdmm.service.news.NewsInfoService;
import cn.mdmm.service.system.SysDictService;
import cn.mdmm.service.type.TypeInfoService;
import cn.modoumama.common.annotation.OpLog;
import cn.modoumama.common.exception.ServiceException;
import cn.modoumama.common.exception.SystemException;
import cn.modoumama.common.utils.JSONUtils;
import cn.modoumama.page.GridDataModel;
import cn.modoumama.page.Page;

@Controller
@RequestMapping(value = "/content")
@OpLog(logDesc="内容管理")
public class NewsInfoController extends BaseController {
	
	@Autowired
	NewsInfoService newsInfoService;
	@Autowired
	TypeInfoService typeInfoService;
    @Autowired
    private SysDictService sysDictService;
	
	/**
	 * 新闻页面
	 * @param request
	 * @param newsType
	 * @return
	 */
	@RequestMapping(value = "/{typeEnglishName}/init")
	public String init(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName){
		Map<String, String> typeMap  = typeInfoService.getAllTypeToMap(typeEnglishName);
		Map<String, String> languageMap = sysDictService.getDetailValueDetailDescMap("语言");
        Map<String, String> statusMap = sysDictService.getDetailValueMap("发布状态");
        Map<String, String> levelMap = sysDictService.getDetailValueMap("级别");
        request.setAttribute("statusMap", JSONUtils.toJson(statusMap));
        request.setAttribute("statusCombo", JSONUtils.toCombo(statusMap));
		request.setAttribute("typeMap", JSONUtils.toJson(typeMap));
		request.setAttribute("typeCombo", JSONUtils.toCombo(typeMap));
		request.setAttribute("levelMap", JSONUtils.toJson(levelMap));
		request.setAttribute("levelCombo", JSONUtils.toCombo(levelMap));
		request.setAttribute("languageMap", JSONUtils.toJson(languageMap));
		request.setAttribute("languageCombo", JSONUtils.toCombo(languageMap));
		return "content/"+typeEnglishName+"/init";
	}
	
	/**
	 * <p>获取新闻列表</p>  
	 * @param request
	 * @param language
	 * @param title
	 * @param type
	 * @param level
	 * @return   
	 * 创建人：邓强   <br>
	 * 创建时间：2017年11月7日 下午4:43:32    <br>
	 */
	@RequestMapping(value = "/{typeEnglishName}/list")
	@ResponseBody
	@OpLog(logDesc="获取新闻列表")
	public ResponseBodyToGridData findByConditions(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName, String language,String title, Integer type,Integer level){
		ResponseBodyToGridData responseBodyToGridData = new ResponseBodyToGridData();
		type = typeInfoService.getTypeId(typeEnglishName, type);
		try{
			Page po = getPage(request, "`PUBLISH_DATE` DESC");
			po.addCondition("language", language);
			po.addCondition("title", title);
			po.addCondition("type", type);
			po.addCondition("level", level);
			GridDataModel gridDataModel = newsInfoService.getGridDataModelByCondition(po);
			responseBodyToGridData.setData(gridDataModel);
		} catch(Exception e){
			logger.error("获取新闻列表", e);
			responseBodyToGridData.addErrInfo("999", "获取新闻列表异常", null);
		}
		return responseBodyToGridData;
	}
	
	@RequestMapping(value = { "info", "{englishTypeName}/{id}" })
	@ResponseBody
	public NewsInfoModel info(HttpServletRequest request, @PathVariable("englishTypeName") String englishTypeName,@PathVariable("id") Long id) {
		request.setAttribute("englishParentTypeName", "news");
		request.setAttribute("englishTypeName", englishTypeName);
		NewsInfoModel news = newsInfoService.getNewsInfo(id);
		return news;
	}
	
	@RequestMapping(value = "/{typeEnglishName}/showAdd")
	public String showAdd(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName) throws Exception{
		Map<String, String> languageMap = sysDictService.getDetailValueDetailDescMap("语言");
		request.setAttribute("typeCombo", JSONUtils.toCombo(typeInfoService.getAllChildrenTypeToMap(typeEnglishName)));
		request.setAttribute("languageCombo", JSONUtils.toCombo(languageMap));
		Integer type = typeInfoService.getTypeId(typeEnglishName, null);
		request.setAttribute("type", type);
		return "content/"+typeEnglishName+"/add";
	}
	
	/**
     * @Description: 
     * @param request
     * @param multipartFile
    */
	@RequestMapping(value = "/{typeEnglishName}/insert")
	@OpLog(logDesc="新增新闻")
	public String insert(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName,NewsInfoModel newsInfo){
		Integer type = typeInfoService.getTypeId(typeEnglishName, newsInfo.getType());
		newsInfo.setType(type);
		Date curr = new Date();
		//当前登录的用户
		SysUser sysUser = SpringSecurityUtils.getCurrentUser();
		newsInfo.setLevel(0);
		newsInfo.setCreateBy(sysUser.getId());
		newsInfo.setCreateDate(curr);
		newsInfo.setEditor(sysUser.getId());
		newsInfo.setEditDate(curr);
		newsInfo.setBrowseNum(0);
		newsInfo.setColletNum(0);
		if(newsInfo.getStatus()!= null && newsInfo.getStatus()==2){
			newsInfo.setPublishDate(curr);
		}
		try {
			newsInfoService.insert(newsInfo);
		} catch (SystemException e) {
			return "error";
		}
		return "success";
	}
	
	@RequestMapping(value = "/{typeEnglishName}/showEdit")
	public String showEdit(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName,Long id){
		Map<String, String> languageMap = sysDictService.getDetailValueDetailDescMap("语言");
		request.setAttribute("typeCombo", JSONUtils.toCombo(typeInfoService.getAllChildrenTypeToMap(typeEnglishName)));
		request.setAttribute("languageCombo", JSONUtils.toCombo(languageMap));
		NewsInfoModel news = newsInfoService.findById(id);
		request.setAttribute("news", news);
		return "content/"+typeEnglishName+"/edit";
	}
	
	/**
     * @Description: 
     * @param request
     * @param multipartFile
     * @return
    */
	@RequestMapping(value = "/{typeEnglishName}/update")
	@OpLog(logDesc="修改新闻")
	public String update(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName,NewsInfoModel newsInfo){
		Integer type = typeInfoService.getTypeId(typeEnglishName, newsInfo.getType());
		newsInfo.setType(type);
		Date curr = new Date();
		//当前登录的用户
		SysUser sysUser = SpringSecurityUtils.getCurrentUser();
		newsInfo.setEditor(sysUser.getId());
		newsInfo.setEditDate(curr);
		if(newsInfo.getStatus()!= null && newsInfo.getStatus()==2){
			newsInfo.setPublishDate(curr);
		}
		try {
			newsInfoService.mergeById(newsInfo);
		} catch (SystemException e) {
			return "error";
		}
		return "success";
	}
	
	 /**
     * <p>修改状态</p> 
     * @param request
     * @return
     * @throws Exception   
     * @author 邓强
     * @date 2017年2月24日下午5:05:46
     */
    @RequestMapping("/{typeEnglishName}/updateReceive")
    @ResponseBody
	@OpLog(logDesc="修改新闻")
    public ResponseBodyToOne updateReceive(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName,Integer[] ids,NewsInfoModel newsInfo) throws Exception {
    	ResponseBodyToOne responseBody = new ResponseBodyToOne();
		logger.debug("method: updateReceive()");
    	try {
			//当前登录的用户
			SysUser sysUser = SpringSecurityUtils.getCurrentUser();
			if(newsInfo.getStatus() != null || newsInfo.getLevel() != null){
				newsInfoService.updateNewsInfo(ids, newsInfo, sysUser.getId());
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new SystemException("修改新闻失败");
		}
    	return responseBody;
    }

	@RequestMapping(value = "/{typeEnglishName}/delete")
	@ResponseBody
	@OpLog(logDesc="删除新闻")
	public ResponseBodyToOne delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("typeEnglishName")String typeEnglishName,Long[] ids){
		ResponseBodyToOne responseBody = new ResponseBodyToOne();
		logger.debug("method: delete() ");
		try {
			newsInfoService.removeByIds(ids);
		} catch (Exception e) {
			throw new ServiceException(MessageConstant.SYSTEM_ERROR);
		}
		return responseBody;
	}
}
